﻿using Pay.Common.Encrypt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Pay.Model.Model
{
    public class AlipayModel
    {
        /// <summary>
        /// 排序容器
        /// </summary>
        private SortedList<string, string> Data = new SortedList<string, string>();
        /// <summary>
        /// 放入容器
        /// </summary>
        /// <param name="dic"></param>
        public void PushData(Dictionary<string, string> dic)
        {
            Data.Clear();
            foreach (var item in dic)
            {
                Data.Add(item.Key, item.Value);
            }
        }

        /// <summary>
        /// 生成查询字符串，不包含sign签名字段
        /// </summary>
        /// <returns></returns>
        private string HttpBuildQuery()
        {
            StringBuilder sb = new StringBuilder();
            foreach (var kv in Data)
            {
                if (!string.IsNullOrWhiteSpace(kv.Key) && !string.IsNullOrWhiteSpace(kv.Value))
                {
                    sb.AppendFormat("{0}={1}&", kv.Key, kv.Value.ToString());
                }
            }

            sb.Remove(sb.Length - 1, 1);
            string str = sb.ToString();
            return str;
        }

        public bool Check(string key, string sign)
        {
            var requestSign = CreateSign(key);
            if (sign.Equals(requestSign, StringComparison.CurrentCultureIgnoreCase))
                return true;
            else
                return false;
        }
        /// <summary>
        /// 生成签名
        /// </summary>
        /// <returns></returns>
        public string CreateSign(string key)
        {
            string queryStr = HttpBuildQuery();
            string rStr = Md5Crypt.MD5(queryStr + "&key=" + key);

            return rStr;
        }
    }
}